using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace SqlTools.CodeGenerator.Data
{
	public delegate void TablePropertyOp(TableProperty prop);

	public class TablePropertyCollection : List<TableProperty>
	{
		protected Table _table;

		public TablePropertyCollection(Table table)
		{
			_table = table;
		}

		TableProperty this[string name]
		{
			get
			{
				for ( int i = 0; i < this.Count; i++ )
				{
					if ( this[i].PropertyName == name )
						return this[i];
				}
				return null;
			}
		}

		public TableProperty FindPropertyByColumnName(string columnName)
		{
			foreach ( TableProperty tp in this )
			{
				if ( tp.Type == TablePropertyType.PrimaryKey )
				{
					PrimaryKeyTableProperty pktp = tp as PrimaryKeyTableProperty;

					TableProperty stp = pktp.Properties.FindPropertyByColumnName(columnName);
					if ( stp != null )
						return stp;
				}
				else
				{
					if ( tp.ColumnName == columnName )
						return tp;
				}
			}

			return null;
		}

		public void OperateOnProperties(TablePropertyOp op)
		{
			foreach ( TableProperty tp in this )
			{
				if ( tp.Type == TablePropertyType.PrimaryKey )
				{
					PrimaryKeyTableProperty pktp = tp as PrimaryKeyTableProperty;

					pktp.Properties.OperateOnProperties(op);
				}
				else
				{
					op(tp);
				}
			}
		}

		public void LoadXml(XmlElement xmlElement)
		{
			foreach ( XmlNode node in xmlElement.ChildNodes )
			{
				if ( node.NodeType == XmlNodeType.Element )
				{
					XmlElement xmlProp = node as XmlElement;

					TablePropertyType type = TablePropertyType.Intrinsic;

					string typestring = xmlProp.GetAttribute("Type");

					type = (TablePropertyType)Enum.Parse(typeof(TablePropertyType), typestring);

					switch ( type )
					{
						case TablePropertyType.Intrinsic:
							IntrinsicTableProperty itp = new IntrinsicTableProperty("", _table, "");
							itp.LoadXml(xmlProp);

							this.Add(itp);
							break;
						case TablePropertyType.ForeignKey:
							ForeignKeyTableProperty fktp = new ForeignKeyTableProperty("", _table, "");
							fktp.LoadXml(xmlProp);

							this.Add(fktp);
							break;
						case TablePropertyType.PrimaryKey:
							PrimaryKeyTableProperty pktp = new PrimaryKeyTableProperty("", _table, "");
							pktp.LoadXml(xmlProp);

							this.Add(pktp);
							break;
					}
				}
			}

		}
	}
}
